use crate::models::attributes::{CreateParams, Model};
use axum::debug_handler;
use loco_rs::prelude::*;

#[debug_handler]
async fn create(
    State(ctx): State<AppContext>,
    Json(params): Json<CreateParams>,
) -> Result<Response> {
    let attribute = Model::create(&ctx.db, params).await?;
    format::json(attribute)
}

#[debug_handler]
async fn find_by_id(State(ctx): State<AppContext>, Path(id): Path<String>) -> Result<Response> {
    let attribute = Model::find_by_id(&ctx.db, &id).await?;
    format::json(attribute)
}

#[debug_handler]
async fn find_by_category(State(ctx): State<AppContext>, Path(category): Path<String>) -> Result<Response> {
    let attribute = Model::find_by_category(&ctx.db, &category).await?;
    format::json(attribute)
}

#[debug_handler]
async fn find_by_group(
    State(ctx): State<AppContext>,
    Path(group_id): Path<String>,
) -> Result<Response> {
    let attributes = Model::find_by_group(&ctx.db, &group_id).await?;
    format::json(attributes)
}


#[debug_handler]
async fn delete_by_id(State(ctx): State<AppContext>, Path(id): Path<String>) -> Result<Response> {
    let attribute = Model::find_by_id(&ctx.db, &id).await?;
    attribute.delete(&ctx.db).await?;
    format::json(())
}

pub fn routes() -> Routes {
    Routes::new()
        .prefix("attributes")
        .add("/", post(create))
        .add("/:id", get(find_by_id))
        .add("/category/:category", get(find_by_category))
        .add("/group/:group_id", get(find_by_group))
        .add("/:id", delete(delete_by_id))
}
